<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Config;
use think\Db;
use think\Env;
use app\common\library\OpenApiConfig;
// ======== updc ========
use updc\bean\Algorithm;
use updc\bean\GateWayRequest;

/**
 * 支付接口
 */
class Pay extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 提交订单
     */
    public function submitOrder()
    {
        $params = $this->request->post('');

        // print_r($params);
        // order_no
        // username
        // phone
        // buddha_name
        // buddha_no
        // blessing
        // timespan_title
        // timespan
        // start_time
        // end_time
        // currency
        // money
        // valid_time
        // payed_order_no
        // payed_data
        // refund_order_no
        // refund_data
        // order_status
        // pay_status
        // print_status
        // create_time
        // sndDt  查询订单校验使用

        // filter
        // if (!isset($params['order_no']) || !$params['order_no']) {
        //     $this->error("订单号不正确，请重新提交", []);
        // }
        if (!isset($params['username']) || !$params['username']) {
            $this->error("用户名不正确，请重新提交", []);
        }
        if (!isset($params['phone']) || !$params['phone']) {
            $this->error("手机号不正确，请重新提交", []);
        }
        if (!isset($params['buddha_name']) || !$params['buddha_name']) {
            $this->error("佛像不能为空，请重新选择佛像", []);
        }
        if (!isset($params['buddha_no']) || !$params['buddha_no']) {
            $this->error("佛灯为空，请重新选择佛灯", []);
        }
        if (!isset($params['blessing']) || !$params['blessing']) {
            $this->error("祈福语为空，请重新选择祈福语", []);
        }
        // money
        $money = floatval($this->request->post("totalAmount", 0));
        if (!$money) {
            $this->error("非法的订单金额，请重新选择时长", []);
        }

        // currency
        if (!isset($params['currency']) || !$params['currency']) {
            $params['currency'] = "rmb";
        }
        // 开始时间
        $timespan = Db::name('timespan')->where('name', $params['timespan_title'])->find();
        if (!$timespan) {
            $this->error("时长为空，请重新选择", []);
        }

        $start_time = time();
        $end_time = strtotime('+' . $timespan['month'] . ' month', $start_time);
        $month = $timespan['month'];

        $params['start_time'] = $start_time;
        $params['end_time'] = $end_time;
        $params['timespan'] = $month;
        $params['money'] = $money;
        $params['valid_time'] = time() + 30 * 60;    // 有效截止时间为30分钟
        $params['order_status'] = 1;                 // 订单提交
        $params['pay_status'] = 0;                   // 订单未支付
        $params['print_status'] = 0;                 // 未打印小票              
        $params['create_time'] = time();

        // print_r($params);
        // 检查订单是否存在
        if (Db::name("payment")->where('order_no', $params['order_no'])->find()) {
            $params = Db::name("payment")->where('order_no', $params['order_no'])->find();
            $this->success("订单已提交，正在为您跳转...", $params);
        }
        // 不存在记录，插入数据
        $result = Db::name("payment")->insert($params);
        if ($result) {
            $this->success("订单提交成功，请继续操作。", $params);
        } else {
            $this->error("祈福订单提交失败，请联系管理人员协助。", []);
        }
    }

    /**
     * 获取订单号
     */
    public function getMerOrderId()
    {
        $config     =   Config::get('site');
        
        // filter 
        // if (!isset($config['GZ_APPID']) || !$config['GZ_APPID']) {
        //     $this->error("GZ_APPID为空，请重新选择", []);
        // }
        // if (!isset($config['GZ_busiMerNo']) || !$config['GZ_busiMerNo']) {
        //     $this->error("GZ_busiMerNo为空，请重新选择", []);
        // }
        // if (!isset($config['GZ_PRIVATEKEYPASS']) || !$config['GZ_PRIVATEKEYPASS']) {
        //     $this->error("GZ_PRIVATEKEYPASS为空，请重新选择", []);
        // }
        // if (!isset($config['GZ_CERTIFICATE']) || !$config['GZ_CERTIFICATE']) {
        //     $this->error("GZ_CERTIFICATE为空，请重新选择", []);
        // }
        
        // 时间：年月日时分秒
        $sndDt = date("YmdHis");

        // 生成订单号
        $merOrdrNo = $config['GZ_busiMerNo'] . date("Ymd") . date("His",time()) . str_pad(strval(mt_rand(0, 999)), 3, "0", STR_PAD_BOTH); // 商户订单号

        $data = [
            'merOrderId' => getMerOrderId($merOrdrNo),
            'sndDt' => $sndDt
        ];
        $this->success("成功", $data);
    }

    /**
     * 获取支付链接
     */
    public function getPayUrl()
    {
        // 接收订单参数
        $params = $this->request->post('');

        // print_r($params);exit();
        // 金额
        // $totalAmount    =   intval($this->request->post('totalAmount', 1));
        // if ($totalAmount <= 0) {
        //     $this->error(__('支付金额有误'), null, 0);
        // }
        // 备注信息，姓名、佛像、编号、祈福语、时长等等
        if (!isset($params['username']) || !$params['username']) {
            $this->error("用户名不正确，请重新提交", []);
        }
        if (!isset($params['phone']) || !$params['phone']) {
            $this->error("手机号不正确，请重新提交", []);
        }
        if (!isset($params['buddha_name']) || !$params['buddha_name']) {
            $this->error("佛像不能为空，请重新选择佛像", []);
        }
        if (!isset($params['buddha_no']) || !$params['buddha_no']) {
            $this->error("佛灯为空，请重新选择佛灯", []);
        }
        if (!isset($params['blessing']) || !$params['blessing']) {
            $this->error("祈福语为空，请重新选择祈福语", []);
        }
        // money
        $totalAmount = floatval($this->request->post("money", 0)) * 100;
        if (!$totalAmount) {
            $this->error("非法的订单金额，请重新选择时长", ["error_msg"=>"非法的订单金额，请重新选择时长"]);
        }

        // currency
        if (!isset($params['currency']) || !$params['currency']) {
            $params['currency'] = "rmb";
        }
        // 开始时间
        $timespan = Db::name('timespan')->where('name', $params['timespan_title'])->find();
        if (!$timespan) {
            $this->error("时长为空，请重新选择", []);
        }

        $start_time = time();
        $end_time = strtotime('+' . $timespan['month'] . ' month', $start_time);
        $month = $timespan['month'];

        $params['start_time'] = $start_time;
        $params['end_time'] = $end_time;
        $params['timespan'] = $month;
        $params['money'] = $totalAmount;
        $params['valid_time'] = time() + 30 * 60;    // 有效截止时间为30分钟
        $params['order_status'] = 1;                 // 订单提交
        $params['pay_status'] = 0;                   // 订单未支付
        $params['print_status'] = 0;                 // 未打印小票              
        $params['create_time'] = time();

        // 接收订单信息 end
        ///////////////////////////////////////////////////////////////////////////////////////////
        // 时间：年月日时分秒
        $sndDt          =   date("YmdHis");
        // 生成订单号
        $merOrdrNo      =   generate_order_id(); 

        // 商家店铺编号
        $config         =   Config::get('site');
        $busiMerNo      =   $config['GZ_busiMerNo'];

        $bizContentJson =   '{"sndDt":"'.$sndDt.'","busiMerNo":"' . $busiMerNo . '","msgBody":{"trxTtlAmt":"' . $totalAmount . '","trxCurr":"CNY","subject":"条码支付","ordrDesc":"支付","oprId":"9527XX","trxTrmNo":"1000001","trxTrmIp":"127.0.0.1","timeoutExpress":"5m","buyerInf":{"bankCode":"00000000","acctType":"0","limitCreditPay":"0"},"sceneInf":{"storeId":"10006","storeNm":"一间小店","areaCode":"5810","address":"广州"},"goodsDtl":[{"gdsId":"1001","gdsPlfId":"10009","gdsNm":"一件商品","gdsCnt":"1","gdsPrice":"1000","gdsCstPrice":"1000","gdsCtgy":"10010","gdsDesc":"商品描述","showUrl":"127.0.0.1"}],"trxType":"NATIVE","trxTrmInf":{"trxTrmType":"08","trxTrmNo":"10086","trxTrmIp":"10.10.0.1","trxTrmMac":"F0E1D2C3B4A5","trxTrmImei":"10002","trxTrmImsi":"10003","trxTrmIccid":"10001","trxTrmWifiMac":"10004"},"rskInf":{"devId":"10000","devcMode":"设备型号XXX","devcLanguage":"JAV","devcLocation":"116.360207","devcNumber":"10086","devcSimNumber":"2"},"merOrdrNo":"'. $merOrdrNo . '","bizFunc":"111011","busiId":"00250029","remark":"remark","remark1":"remark1","remark2":"remark2","remark3":"remark3","remark4":""},"notifyUrl":"http://192.168.180.116:8080/gnete-upbc-merdemo/resultNotifyServlet","remark":"商户联调测试"}';
        
		//请求客户端对象
		$client=OpenApiConfig::getClient();
		//设置加密算法类型
		$client->__set("algorithm",Algorithm::SHA256withRSA);

		//设置公共请求参数对象
		$gateWayRequest=new GateWayRequest();
		//服务名
		$gateWayRequest->__set("apiInterfaceId","gnete.upbc.code.trade");
		//方法名
		$gateWayRequest->__set("methodName","precreate");
		//版本号
		$gateWayRequest->__set("version","1.0.1");
		$gateWayRequest->__set("bizContent",$bizContentJson);

		$client->__set("gateWayRequest",$gateWayRequest);

		$flag   =   $client->apiRequest();
		//  if($flag==1){
		//  	echo "请求发送成功，响应验签成功\n";
		//  }else{
		//  	echo "请求发送成功，响应验签失败\n";
		//  }
		//  echo "请求主体：\n";
		//  var_dump($client->__get("requestBody")) . '\n<br/><br/>';

		//  echo "响应主体：\n";
		//  var_dump($client->__get("responseBody"));
        //  echo "<br/><br/>";
        
        $result = json_decode($client->__get("responseBody"), true);

        if ($result['response']['subCode'] != '000000') {
            $this->error(__('系统错误，请联系管理员'), "");
        }

        // 请求支付链接成功后，添加订单信息
        $params['order_no'] =   $merOrdrNo;
        $params['sndDt']    =   $sndDt;
        // // 检查订单是否存在
        if (Db::name("payment")->where('order_no', $merOrdrNo)->find()) {
            $params = Db::name("payment")->where('order_no', $merOrdrNo)->find();
            $this->error("订单已提交，请勿重复提交", $params);
        }

        // // 不存在记录，插入数据
        $res = Db::name("payment")->insert($params);

        $data = [
            'payurl'        =>  $result['response']['msgBody']['qrCode'],
            'merOrderId'    =>  $merOrdrNo,
            'totalAmount'   =>  $totalAmount,
            'sndDt'         =>  $sndDt
        ];

        $this->success("成功", $data);
    }

    /**
     * 支付查询
     */
    public function payQuery()
    {
        $oriTrxDt       =   $this->request->param("oriTrxDt");
		$oriMerOrdrNo   =   $this->request->param("oriMerOrdrNo");

		if(empty($oriTrxDt) || empty($oriMerOrdrNo)) {
			$this->error(__('参数有误'), []);
			exit();
		}
        
		// 时间：年月日时分秒
		$sndDt = date("YmdHis");	

        // 商家店铺编号
        $config         =   Config::get('site');
        $busiMerNo      =   $config['GZ_busiMerNo'];

		// 动态生成订单号
		// $merOrdrNo = "898350308989301". date("Ymd") . "093637001"; // 商户订单号
		$merOrdrNo = generate_order_id();
		$bizContentJson='{"sndDt":"' . $sndDt . '","busiMerNo":"' . $busiMerNo . '","msgBody":{"merOrdrNo":"' . $merOrdrNo . '","oriMerOrdrNo":"' . $oriMerOrdrNo . '","oriTrxDt":"' . $oriTrxDt . '","bizFunc":"611011","remark":"xxx","remark1":"xxx","remark2":"xxx"}}';

		//请求客户端对象
		$client=OpenApiConfig::getClient();
		//设置加密算法类型
		$client->__set("algorithm",Algorithm::SHA256withRSA);

		//设置公共请求参数对象
		$gateWayRequest=new GateWayRequest();
		//服务名
		$gateWayRequest->__set("apiInterfaceId","gnete.upbc.cashier.trade");
		//方法名
		$gateWayRequest->__set("methodName","payQuery");
		//版本号
		$gateWayRequest->__set("version","1.0.1");
		$gateWayRequest->__set("bizContent",$bizContentJson);

		$client->__set("gateWayRequest",$gateWayRequest);

        $flag=$client->apiRequest();
        // if($flag==1){
        // echo "请求发送成功，响应验签成功\n";
        // }else{
        // echo "请求发送成功，响应验签失败\n";
        // }

        // echo "请求主体：\n";
        // var_dump($client->__get("requestBody"));

        // echo "响应主体：\n";
        // var_dump($client->__get("responseBody"));		

        // echo "<br/><br/>";
        // print_r($client->__get("responseBody"));

        $result = json_decode($client->__get("responseBody"), true);

        if ($result['response']['subCode'] != '000000') {
            $this->error(__('系统错误，请联系管理员'), []);
        }

        if(!isset($result['response']['msgBody']['trxCode']) || $result['response']['msgBody']['trxCode'] = '370002'){
            $this->error(__('订单未支付'), []);
        }

        $data = [
            'merOrderId'    =>  $oriMerOrdrNo,
            'sndDt'         =>  $oriTrxDt
        ];
        
        // echo $result;
        // 将支付成功的结果写入数据库
        // 请求订单的同时，判断订单是否已经支付成功，支付成功，写入状态为1，支付失败，写入状态为2
        $result = Db::name("payment")->where('order_no', $oriMerOrdrNo)->update(['order_status' => 1, 'pay_status' => 1, 'print_status' => 0]);

        // 调用小票接口，打印小票
        if ($result) {
            // 打印小票
        }
        // add code here

        $this->success("成功", $data);
    }

}
